<?php
/**
 * Created by PhpStorm.
 * User: huawei
 * Date: 2021/11/1
 * Time: 11:20
 */
namespace yuexiu;
use think\facade\Env;
use think\Db;
class Client
{
    public $domain = "https://fangbao-api.yuexiuproperty.cn/yx-external-docking";
    public $appId ="ec4293f8";
    public $appSecret ="1234567890abcdef";
    public $gameid = "xingteng";

    /**
     * @title 获取用户信息
     * @desc 测试用userid oKTJA5bsSe6P_OgcA0UGBubhGXU4,oKTJA5X1VFLt3oEaGmuU8HRZQ9II
     * @param $user_id
     * @return mixed
     */
    public function getuserinfo($user_id){
        $url = $this->domain."/platform/visitor";

        $rs = httpPost($url,json_encode($this->getsign(["userId"=>$user_id])));

        if($rs){
            $result = $this->res($rs);
            $userId = $result['userId'];
            $filepath = "/upload/avatar_{$userId}.png";
            $newpath = Env::get('root_path').'public'.$filepath;

            if(!is_file($newpath)){
                $img = file_get_contents($result["avatarUrl"]);
                file_put_contents($newpath,$img);
                $result["avatarUrl"] = request()->domain().$filepath;
            }else{
                $result["avatarUrl"] = request()->domain().$filepath;
            }

            return $result;
        }else{
            errMsg("思为用户信息获取失败");
        }
    }

    /**
     * @title 创建二维码
     * @param $suser
     * @param $poster
     * @param $userId
     * @param $visitorStatus
     * @return string
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function createqrcode($suser,$poster,$userId,$visitorStatus){

        $file = Db::name("qrcode")->where("user_id",$suser)
            ->where("typec",$poster)->field("id,qrcode,cnum")->find();
        if($file){
            Db::name("qrcode")->where("id",$file["id"])->update([
                "cnum"=>$file["cnum"]+1
            ]);
            return request()->domain().$file["qrcode"];
        }else{
            $sceneCode = 'suser='.$suser."&poster=".$poster;
            $area = AREA;
            $h5url = url("index/index/index","",false,true).'?organizationCode=organization_'.$area.'&suser='.$suser."&poster=".$poster."&visitorStatus=".$visitorStatus;
            $url = $this->domain."/platform/qrCodeUrl";
            $rs = httpPost($url,json_encode($this->getsign(["userId"=>$userId,"sceneCode"=>$sceneCode,"url"=>$h5url])));
            if($rs){
                $data = $this->res($rs);
                $file = $data["url"];
                $img = file_get_contents($file);
                $filepath = "/upload/{$userId}.png";
                $newpath = Env::get('root_path').'public'.$filepath;
                file_put_contents($newpath,$img);

                Db::name("qrcode")->insert([
                    "user_id"=>$suser,
                    "typec"=>$poster,
                    "qrcode"=>$filepath,
                    "qrcodeid"=>isset($data["uuid"])?$data["uuid"]:"",
                    "add_time"=>date("Y-m-d H:i:s")
                ]);
                return request()->domain().$filepath;
            }else{
                errMsg("思为二维码获取失败");
            }
        }
    }

    /**
     * @title 获取红包配置
     */
    public function getredbaglist(){
        $data=[
            "page"=>1,
            "pageSize"=>100
        ];
        $url = $this->domain."/platform/redPack/query";
        $rs = httpPost($url,json_encode($this->getsign($data)));
        $data = $this->res($rs);
        var_dump($data);
    }

    /**
     * @title 发红包
     * @param $packid
     * @param $userId
     */
    public function sendredbag($packid,$userId){
        $data=[
            "gameId"=>$this->gameid,
            "packConfigId"=>$packid,
            "userId"=>$userId
        ];
        $url = $this->domain."/platform/redPack/send";

        $rs = httpPost($url,json_encode($this->getsign($data)));

        $data = $this->res($rs);
    }

    /**
     * @title 卡券列表
     */
    public function couponlist(){
        $url = $this->domain."/platform/prize/list";
        $data = [
            "activityCode"=>1
        ];
        $rs = httpPost($url,json_encode($this->getsign($data)));
        $data = $this->res($rs);
    }



    public function sendcoupon(){
        $url = $this->domain."/platform/prize/send";
    }



    public function res($rs){
        $result = json_decode($rs,true);
        if(!isset($result['code'])){
            errMsg(isset($result["msg"])?$result["msg"]:"接口出错");

        }
        if($result&&$result['code']==200){
            return $result["data"];
        }else{
            errMsg(isset($result["msg"])?$result["msg"]:"接口出错");

        }
    }
    public function getsign($data){
        $params = $data;
        $params["appId"] = $this->appId;
        $params["sign_key"] = $this->appSecret;
        $timestamp = time();
        $params["timestamp"] = (string)$timestamp;

        $md5string = $this->makePreString($params);

        $sign = md5($md5string);

        $data["appId"] = $this->appId;
        $data["sign"] = $sign;
        $data["timestamp"] = $timestamp;

        return $data;
    }
    public function  makePreString($params)
    {
        $params['sign_key'] = $this->appSecret;
        $params = filterParams($params);
        // 按参数键名排序参数
        ksort($params);
        // 参数连接⽅式：age=12&name=张三&sex=male
        $preString = urldecode(http_build_query($params));
        return $preString;
    }
    /**
     * 过滤参数值
     * @param array $params
     * @return array
     */
    public function filterParams($params = [])
    {
        $filtered = array_filter($params, function ($value,$key) {
            // 排除空值
            if (in_array($value, ['',null,false],true)) {
                return false;
            }
            // 排除不参与加密的参数
            if (in_array($key,['sign'])) {
                return false;
            }
            return true;
        });
        return $filtered;
    }
}
